package cn.qrx.gateway.datasource.connection;

import cn.qrx.gateway.datasource.Connection;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * @Author: 屈燃希
 * @Date: 2025/10/20
 * @Version: V1.0
 * @Description:
 */
public class DubboConnection implements Connection {

    private ApplicationConfig applicationConfig;

    private RegistryConfig registryConfig;

    private ReferenceConfig<GenericService> reference;

    public DubboConnection(ApplicationConfig applicationConfig, RegistryConfig registryConfig, ReferenceConfig<GenericService> reference) {
        this.applicationConfig = applicationConfig;
        this.registryConfig = registryConfig;
        this.reference = reference;
    }

    @Override
    public Object execute(String method, String[] parameterTypes, String[] parameterNames, Object[] args) {
        // 构建Dubbo服务
        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        bootstrap.application(applicationConfig).registry(registryConfig).reference(reference).start();
        // 获取泛化调用服务
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        GenericService genericService = cache.get(reference);

        return genericService.$invoke(method,parameterTypes,args);
    }
}
